package com.a.module_home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ReflectUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.myframe.BaseNetApp;
import com.example.myframe.DistDeptApp;
import com.example.myprint.utils.XmlUtil;
import com.a.lib_base.base.ui.BaseActivityViewBinding;
import com.a.lib_bean.PermissionUtil;
import com.a.lib_bean.bean.Employee;
import com.a.lib_bean.bean.PermissionBean;
import com.a.lib_bean.enums.HomeItemType;
import com.a.lib_route.login.LoginNav;
import com.a.lib_utils.DialogUtil;
import com.a.lib_utils.TipUtil;
import com.a.module_home.databinding.ActivityHomeBinding;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tencent.mmkv.MMKV;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.example.myprint.consts.Constant2.CODED_CONTENT;

@Route(path = "/home/home", group = "home")
public class HomeActivity extends BaseActivityViewBinding<ActivityHomeBinding> implements OnItemClickListener {

    private static final String TAG = HomeActivity.class.getSimpleName();
    private Employee employee;

    @Autowired
    String selectItemPath;

    @SuppressLint("NonConstantResourceId")
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MMKV mmkv = MMKV.defaultMMKV();
        ARouter.getInstance().inject(this);
        b.tvEmployeeID.setText(DistDeptApp.getEmployee().getEmployeeName());
        b.textView8.setText(BaseNetApp.moduleName);
        //更新完成后告知用户更新了什么功能
        boolean tip = mmkv.decodeBool("updateContent_" + BaseNetApp.APP_VERSION, true);
        if (tip) {
            mmkv.encode("updateContent_" + BaseNetApp.APP_VERSION, false);
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("更新内容")
                    .setMessage("1.更新了待进货显示的内容")
                    .addAction("确定", (dialog, index) -> dialog.dismiss())
                    .show();
        }
        TipUtil.toast("点击左上角名称可以退出登录");
        b.tvEmployeeID.setOnClickListener(v -> {
            TipUtil.toast("退出登录");
            LoginNav.INSTANCE.routerMain();
            finish();
        });

        /*showSettingDialog() 未来需要修改时改用这个方法*/
        b.ivSetUp.setOnClickListener(v -> TipUtil.toast("厂区ID：" + DistDeptApp.distDeptID));
        List<Home> workbenchList = new ArrayList<>();
        List<Home> storageList = new ArrayList<>();
        List<Home> otherList = new ArrayList<>();
        /*测试用，不用判断权限，添加全部*/
        for (PermissionBean pre : PermissionUtil.getPermissionSet()) {
            String name = pre.getName();
            if (name != null) {
                //  TODO: 2022/7/12 此处耦合了
                if (name.equals("生产入库")) {
                    workbenchList.add(new Home("成品生产入库", pre.getImgId()));
                    workbenchList.add(new Home("半成品生产入库", R.drawable.ic_have_half_stock));
                    continue;
                } else if (name.equals("生产领料")) {
                    workbenchList.add(new Home("成品生产领料", pre.getImgId()));
                    workbenchList.add(new Home("半成品生产领料", R.drawable.ic_semifinished_production_pick));
                    continue;
                }
                final HomeItemType homeItemType = pre.getHomeItemType();
                if (homeItemType == HomeItemType.WORKBENCH) {
                    workbenchList.add(new Home(name, pre.getImgId()));
                } else if (homeItemType == HomeItemType.STORAGE) {
                    storageList.add(new Home(name, pre.getImgId()));
                } else {
                    otherList.add(new Home(name, pre.getImgId()));
                }
            }
        }
        setSelectItem();
        initAd(workbenchList, b.rvWorkbench);
        initAd(storageList, b.rvStorage);
        initAd(otherList, b.rvOther);
    }

    private void initAd(List<Home> list, RecyclerView rv) {
        if (list.size() == 0) {
            return;
        }
        HomeRvAdapter ad = new HomeRvAdapter(list);
        ad.setOnItemClickListener(this);
        rv.setLayoutManager(new GridLayoutManager(this, 4));
        rv.setAdapter(ad);
    }

    @Override
    public String setTitle() {
        return null;
    }

    @Override
    public int setBarBackground() {
        return 0;
    }

    @Override
    public ActivityHomeBinding viewBinding(ViewGroup view) {
        return ActivityHomeBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Employee newEmployee = (Employee) intent.getSerializableExtra("user");
        if (this.employee == null || !this.employee.equals(newEmployee)) {
            this.employee = newEmployee;
        }
    }


    public static void actionStart(Context context, @Nullable Integer intentFlag, @Nullable Employee employee) {
        Intent intent = new Intent(context, HomeActivity.class);
        if (intentFlag != null) {
            intent.setFlags(intentFlag);
        }
        if (employee != null) {
            intent.putExtra("user", employee);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        TipUtil.dismiss();
    }


    private static final int REQUEST_CODE_SCAN = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传

        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
//                //返回的文本内容
                String content = data.getStringExtra(CODED_CONTENT);
//                //返回的BitMap图像
//                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                Log.d(TAG, "onActivityResult:" + content);
            }
        }
    }

    //屏蔽返回键的代码:
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //设置的弹窗
    private void showSettingDialog() {
        QMUIDialog.EditTextDialogBuilder editTextDialog = DialogUtil.getEditTextDialog(this);
        editTextDialog.setTitle("设置DistDeptID").setDefaultText(XmlUtil.readFileSdcard("DistDeptID")).setPlaceholder("请输入")
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    String s = editTextDialog.getEditText().getText().toString();
                    XmlUtil.writeFileSdcard("DistDeptID", s);
                    DistDeptApp.distDeptID = s;
                    TipUtil.toast("修改成功");
                    dialog.dismiss();
                }).show();
    }

    private ISelectItem selectItem;

    /*通过反射获取指定目录的类*/
    private void setSelectItem() {
        selectItem = ReflectUtils.reflect(selectItemPath).newInstance().get();
    }

    @Override
    public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        final Home item = (Home) adapter.getItem(position);
        selectItem.select(item.getImgId());
    }

}
